package texture;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class SimpleResource implements Resource {
	private final Map<String, MetadataSection> mapMetadataSections = new HashMap<>();
	private final ResourceLocation srResourceLocation;
	private final InputStream resourceInputStream;
	private final InputStream mcmetaInputStream;
	private final MetadataSerializer srMetadataSerializer;

	private boolean mcmetaJsonChecked;
	private JsonObject mcmetaJson;

	public SimpleResource(ResourceLocation par1ResourceLocation, InputStream par2InputStream, InputStream par3InputStream,
			MetadataSerializer par4MetadataSerializer) {
		this.srResourceLocation = par1ResourceLocation;
		this.resourceInputStream = par2InputStream;
		this.mcmetaInputStream = par3InputStream;
		this.srMetadataSerializer = par4MetadataSerializer;
	}

	public InputStream getInputStream() {
		return this.resourceInputStream;
	}

	public boolean hasMetadata() {
		return this.mcmetaInputStream != null;
	}

	@Override
	public MetadataSection getMetadata(String par1Str) {
		if (!this.hasMetadata()) {
			return null;
		}
		
		if (this.mcmetaJson == null && !this.mcmetaJsonChecked) {
			this.mcmetaJsonChecked = true;
			BufferedReader bufferedreader = null;

			try {
				bufferedreader = new BufferedReader(new InputStreamReader(this.mcmetaInputStream));
				this.mcmetaJson = (new JsonParser()).parse(bufferedreader).getAsJsonObject();
			} finally {
				try {
					if (bufferedreader != null) {
						bufferedreader.close();
					}
				} catch (IOException ioe) {
					// ignore
				}
			}
		}

		MetadataSection metadatasection = this.mapMetadataSections.get(par1Str);

		if (metadatasection == null) {
			metadatasection = this.srMetadataSerializer.parseMetadataSection(par1Str, this.mcmetaJson);
		}

		return metadatasection;
	}

	public ResourceLocation getSrResourceLocation() {
		return srResourceLocation;
	}
}
